//************************************************************
//	COPYRIGHT 2011 Birthin' Hips - ALL RIGHTS RESERVED
//************************************************************
//
//	$Id: Logger.java$
//
//	$Date: 12/13/11$
//
//	Reason: Logs messages coming off the write queue (verified or not) to an external file, 
//  and also prints them out on standard output
//
//*************************************************************

/** $Author: Colton Presler, Ross Kahn, Elysia Haight$ */
/** $Revision: $ */

package com;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

//==============================================================
public class Logger {
	public static final String DEFAULT_FILE_NAME = "log.txt";	// File name to write to
	public static final String INVALID = "INVALID";				// Text to append to message if message is flagged as invalid
	
	private int lineCount = 0;
	
	/**
	 *  Construct the Logger and delete the previous log file if it exists
	 */
	//----------------------------------------------------------
	public Logger(){
		File logFile = new File(DEFAULT_FILE_NAME);
		if(logFile.exists()){
			logFile.delete();
		}
	}
	
	/**
	 * Opens a filestream and appends the given message to the default
	 * file. If the message invalid flag is true then the logger will
	 * emphasize that the message is not valid.
	 * 
	 * @param message the message to be logged
	 * @param invalid was the message invalid
	 */
	//----------------------------------------------------------
	public void log(Message message, boolean valid){
		lineCount ++;
		
		if(valid){
			// Message was verified in both sequence and content by the ProducerThread 
			log(message.toString() + "\n");
		}else{
			log( INVALID + " " + message.toString() + "\n" );
		}
		
	}
	
	/**
	 * Opens the filestream, appends the string to it, and then closes the filestream.
	 * 
	 * @param message string to be appended to file
	 */
	//----------------------------------------------------------
	private void log(String message){
		try {
			 // Creates the filestream open for appending
			FileWriter fstream = new FileWriter("log.txt", true);			
			BufferedWriter file = new BufferedWriter(fstream);
			
			file.write(lineCount + "    " + message);
			System.out.println(lineCount + "    " + message);
			
			file.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	
	
}
